package com.carbeauty.service.impl;

import com.carbeauty.entity.User;
import com.carbeauty.repository.UserRepository;
import com.carbeauty.common.enums.BusinessStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Spring Security 用户详情服务实现类
 * 
 * 实现Spring Security的UserDetailsService接口:
 * - 根据用户名加载用户信息
 * - 构建用户权限信息
 * - 处理用户状态验证
 * 
 * @author CarBeauty Team
 */
@Service("userDetailsService")
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {
    
    @Autowired
    private UserRepository userRepository;
    
    /**
     * 根据用户名加载用户详情
     * 
     * @param username 用户名
     * @return UserDetails 用户详情
     * @throws UsernameNotFoundException 用户不存在异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查找用户
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + username));
        
        // 检查用户状态
        if (!BusinessStatus.ACTIVE.equals(user.getStatus())) {
            throw new UsernameNotFoundException("用户已被禁用: " + username);
        }
        
        // 构建用户权限
        Collection<GrantedAuthority> authorities = buildUserAuthorities(user);
        
        // 创建Spring Security用户对象
        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(authorities)
                .accountExpired(false)
                .accountLocked(false)
                .credentialsExpired(false)
                .disabled(!user.isActive())
                .build();
    }
    
    /**
     * 构建用户权限列表
     * 
     * @param user 用户实体
     * @return 权限集合
     */
    private Collection<GrantedAuthority> buildUserAuthorities(User user) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        
        // 添加角色权限
        authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getRole().name()));
        
        // 根据角色添加具体权限
        switch (user.getRole()) {
            case ADMIN:
                // 管理员拥有所有权限
                authorities.add(new SimpleGrantedAuthority("PERM_SYSTEM_MANAGE"));
                authorities.add(new SimpleGrantedAuthority("PERM_USER_MANAGE"));
                authorities.add(new SimpleGrantedAuthority("PERM_CUSTOMER_MANAGE"));
                authorities.add(new SimpleGrantedAuthority("PERM_ORDER_MANAGE"));
                authorities.add(new SimpleGrantedAuthority("PERM_MATERIAL_MANAGE"));
                authorities.add(new SimpleGrantedAuthority("PERM_SERVICE_MANAGE"));
                authorities.add(new SimpleGrantedAuthority("PERM_FINANCE_MANAGE"));
                authorities.add(new SimpleGrantedAuthority("PERM_REPORT_VIEW"));
                authorities.add(new SimpleGrantedAuthority("PERM_DICT_MANAGE"));
                break;
                
            case MANAGER:
                // 店长权限
                authorities.add(new SimpleGrantedAuthority("PERM_CUSTOMER_MANAGE"));
                authorities.add(new SimpleGrantedAuthority("PERM_ORDER_MANAGE"));
                authorities.add(new SimpleGrantedAuthority("PERM_MATERIAL_MANAGE"));
                authorities.add(new SimpleGrantedAuthority("PERM_SERVICE_MANAGE"));
                authorities.add(new SimpleGrantedAuthority("PERM_FINANCE_MANAGE"));
                authorities.add(new SimpleGrantedAuthority("PERM_REPORT_VIEW"));
                authorities.add(new SimpleGrantedAuthority("PERM_EMPLOYEE_MANAGE"));
                break;
                
            case EMPLOYEE:
                // 员工权限
                authorities.add(new SimpleGrantedAuthority("PERM_CUSTOMER_MANAGE"));
                authorities.add(new SimpleGrantedAuthority("PERM_ORDER_MANAGE"));
                authorities.add(new SimpleGrantedAuthority("PERM_MATERIAL_VIEW"));
                authorities.add(new SimpleGrantedAuthority("PERM_SERVICE_VIEW"));
                break;
                
            case CUSTOMER:
                // 客户权限
                authorities.add(new SimpleGrantedAuthority("PERM_PROFILE_VIEW"));
                authorities.add(new SimpleGrantedAuthority("PERM_ORDER_VIEW"));
                authorities.add(new SimpleGrantedAuthority("PERM_RECHARGE_MANAGE"));
                break;
                
            default:
                // 默认权限
                authorities.add(new SimpleGrantedAuthority("PERM_BASIC"));
                break;
        }
        
        return authorities;
    }
}
